//
//  NetworkTools.swift
//  测试-05-AFN Swift
//
//  Created by male on 15/10/15.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
import AFNetworking

/// HTTP 请求方法枚举
enum HMRequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

// MARK: 网络工具
class NetworkTools: AFHTTPSessionManager {
    
    /// 应用程序信息
    private let appKey = "540249436"
    private let appSecret = "7dad7fc996b75e17db8226c8a29ad53e"
    private let redirectUrl = "http://www.baidu.com"

    // 网络请求完成回调
    typealias HMRequestCallBack = (result: AnyObject?, error: NSError?) -> ()
    
    // 单例
    static let sharedTools: NetworkTools = {
        
        let tools = NetworkTools(baseURL: nil)
        
        // 设置反序列化数据格式 - 系统会自动将 OC 框架中的 NSSet 转换成 Set
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
    
    /// token 字典
    private var tokenDict: [String: AnyObject]? {
        
        // 判断 token 是否有效  key 值一定跟文档里面的相同
        if let token = UserAccountViewModel.sharedUserAccountModel.accessToken {
            return ["access_token": token]
        }
        return nil
    }
}

// MARK: - 微博相关方法
extension NetworkTools {
    
    ///  加载微博数据
    ///
    ///  - parameter finished: 完成回调
    ///  - see: [https://api.weibo.com/2/statuses/home_timeline.json](https://api.weibo.com/2/statuses/home_timeline.json)
    func loadStatus(finished: HMRequestCallBack) {
        
        guard let parameters = tokenDict else {
            finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message": "token 为空"]))
            
            print("token 为空")
            return
        }
        let urlStr = "https://api.weibo.com/2/statuses/home_timeline.json"
        request(.GET, URLString: urlStr, parameters: parameters, finished: finished)
    }
}

// MARK: - 用户相关方法
extension NetworkTools {
    
    ///  下载用户信息
    ///
    ///  - parameter uid:          需要查询的用户ID
    ///  - parameter access_token: accessToken
    ///  - parameter finished:     完成回调
    ///  - see: [http://open.weibo.com/wiki/2/users/show](http://open.weibo.com/wiki/2/users/show)
    func loadUserInfo(uid: String, finished: HMRequestCallBack) {
        
        guard var parameters = tokenDict else {
            finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message": "token 为空"]))
            return
        }
//
        let urlStr = "https://api.weibo.com/2/users/show.json"
        parameters["uid"] = uid
        
        request(.GET, URLString: urlStr, parameters: parameters, finished: finished)
    }
}

// MARK: - OAuth 相关方法
extension NetworkTools {
    
    /// 加载 OAuth 授权页面
    /// - see : [http://open.weibo.com/wiki/Oauth2/authorize](http://open.weibo.com/wiki/Oauth2/authorize)
    var authURL: NSURL {
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUrl)"
        
        return NSURL(string: urlStr)!
    }
    
    ///  加载 AccessToken
    func loadAccessToken(code: String, finished: HMRequestCallBack) {
        
        let urlStr: String = "https://api.weibo.com/oauth2/access_token"
        
        let parameters: [String: AnyObject] = [
            "client_id": appKey,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUrl
        ]
        
        request(.POST, URLString: urlStr, parameters: parameters, finished: finished)
    }
}

// MARK: - 封装 AFN 网络方法
extension NetworkTools {
    
    /// 网络请求
    ///
    /// - parameter method:     GET / POST
    /// - parameter URLString:  URLString
    /// - parameter parameters: 参数字典
    /// - parameter finished:   完成回调
    func request(method: HMRequestMethod, URLString: String, parameters: [String: AnyObject]?, finished: (result: AnyObject?, error: NSError?)->()) {
        
        // 定义成功回调
        let success = { (task: NSURLSessionDataTask, result: AnyObject) -> Void in
            finished(result: result, error: nil)
        }
        
        // 定义失败回调
        let failure = { (task: NSURLSessionDataTask, error: NSError) -> Void in
            // 在开发网络应用的时候，错误不要提示给用户，但是错误一定要输出！
            print(error)
            finished(result: nil, error: error)
        }
        
        if method == HMRequestMethod.GET {
            GET(URLString, parameters: parameters, success: success, failure: failure)
        } else {
            POST(URLString, parameters: parameters, success: success, failure: failure)
        }
    }
}
